import React, { useState } from "react";
import {
  Upload,
  Button,
  Input,
  Card,
  message,
  Typography,
  Space,
  Divider,
} from "antd";
import { UploadOutlined, CopyOutlined } from "@ant-design/icons";
import type { UploadFile, UploadProps, RcFile } from "antd/es/upload/interface";
import IconFont from "../../../components/IconFont";
import ToolTitle from "@/components/ToolTitle";
import { imgToolsData } from "@/components/ToolsData";

const { TextArea } = Input;
const { Text } = Typography;

const ImageAndBase64: React.FC = () => {
  const [base64String, setBase64String] = useState<string>("");
  const [fileList, setFileList] = useState<UploadFile[]>([]);

  const handleFileChange: UploadProps["onChange"] = ({
    fileList: newFileList,
  }) => {
    setFileList(newFileList);
    if (newFileList.length > 0 && newFileList[0].originFileObj) {
      convertToBase64(newFileList[0].originFileObj);
    } else {
      setBase64String("");
    }
  };

  const convertToBase64 = (file: File) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => {
      const result = reader.result as string;
      setBase64String(result);
    };
    reader.onerror = (error) => {
      message.error("转换失败，请重试");
      console.error("转换失败:", error);
    };
  };

  const base64ToFile = (base64: string, filename: string) => {
    const arr = base64.split(",");
    const mime = arr[0].match(/:(.*?);/)?.[1];
    const bstr = atob(arr[1]);
    let n = bstr.length;
    const u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, { type: mime });
  };

  const copyToClipboard = () => {
    if (base64String) {
      navigator.clipboard
        .writeText(base64String)
        .then(() => message.success("已复制到剪贴板"))
        .catch(() => message.error("复制失败，请手动复制"));
    } else {
      message.warning("没有可复制的内容");
    }
  };

  const uploadProps: UploadProps = {
    beforeUpload: (file) => {
      const isValidFormat = /\.(jpg|jpeg|png|gif|webp|svg|ico)$/i.test(
        file.name
      );
      if (!isValidFormat) {
        message.error("只支持 jpg, jpeg, png, gif, webp, svg, ico 格式的图片");
        return Upload.LIST_IGNORE;
      }
      return false;
    },
    fileList,
    onChange: handleFileChange,
    maxCount: 1,
    showUploadList: false,
  };

  return (
    <div className="w-full">
      <Card bordered={false} className="shadow-md">
        <ToolTitle
          title={
            imgToolsData.find((item) => item.title === "图片与Base64互转")
              ?.title || ""
          }
          description={
            imgToolsData.find((item) => item.title === "图片与Base64互转")
              ?.description || ""
          }
        />

        <Divider />

        <div className="mb-3">
          <Upload.Dragger {...uploadProps} className="w-full">
            {fileList.length > 0 ? (
              <div className="w-full flex justify-center relative group">
                <img
                  src={URL.createObjectURL(fileList[0].originFileObj as Blob)}
                  alt="预览图片"
                  className="max-w-full max-h-[400px] object-contain"
                />
                <div className="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity duration-300 bg-black/50">
                  <IconFont
                    className="text-2xl text-white"
                    type="icon-Replace"
                  />
                </div>
              </div>
            ) : (
              <>
                <p className="text-blue-500">
                  <UploadOutlined className="text-5xl" />
                </p>
                <p className="ant-upload-text">
                  拖拽图片文件到此处 或{" "}
                  <Text className="text-blue-500 cursor-pointer">
                    点击选择文件
                  </Text>
                </p>
                <p className="text-gray-500 text-sm mt-2">
                  支持文件格式: jpg, jpeg, png, gif, webp, svg, ico
                </p>
              </>
            )}
          </Upload.Dragger>
        </div>

        <div className="mb-8">
          <div className="flex justify-between items-center mb-4">
            <Text strong>Base64 编码结果</Text>
            <Space>
              <Button
                type="primary"
                icon={<CopyOutlined />}
                onClick={copyToClipboard}
                disabled={!base64String}
              >
                复制到剪贴板
              </Button>
            </Space>
          </div>

          <TextArea
            value={base64String}
            onChange={(e) => {
              setBase64String(e.target.value);
              // 当输入base64字符串时,尝试更新预览图片
              try {
                const file = base64ToFile(e.target.value, "preview.png");
                setFileList([
                  {
                    uid: "-1",
                    name: "preview.png",
                    status: "done",
                    originFileObj: file as RcFile,
                  },
                ]);
              } catch (error) {
                console.error("转换失败:", error);
                // 如果base64格式不正确,清空预览图片
                if (e.target.value === "") {
                  setFileList([]);
                }
              }
            }}
            placeholder="转换后的Base64编码将显示在这里..."
            autoSize={{ minRows: 6, maxRows: 10 }}
            className="w-full"
          />
        </div>
      </Card>
    </div>
  );
};

export default ImageAndBase64;
